<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();

// 权限检查
$funcs = getFuncs($_SESSION['admin_group']);
checkFunc(9900);

$now = time();
$success = $_GET['success'] ?? null;
$error = $_GET['error'] ?? null;
$action = $_GET['action'] ?? null;

if($action) {

}

$total = $DB->count('users');
$pagesize = 20;
$total_page = ceil($total / $pagesize);
$page = $_GET['page'] ?? 1;
if($page < 1) $page = 1;
if($page > $total_page) $page = $total_page;
$start = ($page - 1) * $pagesize;

$all_user = $DB->select('users', '*', ['ORDER'=>['id'=>'DESC'], 'LIMIT'=>[$start, $pagesize]]);

$duck_ids = [];
foreach($all_user as $u) {
    if(!$u['duckId']) continue;
    $duck_ids[] = $u['duckId'];
}
$all_ducks = $DB->select('ducks', '*', ['id'=>$duck_ids]);
$ducks = [];
foreach($all_ducks as $d) {
    $ducks[$d['id']] = $d;
}

display_header();
?>

<style>
    .data_table th {font-size:14px; color:#666; font-weight:normal; width:180px;}
    .data_table td {font-size:18px; font-weight:normal;text-align:right;}
    .data_table td small {font-size:12px; color:#888;margin-left:3px;}
    .data_table td div {padding:0;}
    td,th {vertical-align:middle !important;}
    .filter_box span {border:1px solid #4b97c4; border-radius:5px; padding:4px 7px; margin-right:10px;}
    .modal_table_style td {font-size:16px;}
    .funcs_box {}
    .funcs_box label {font-weight:normal;}
    .funcs_box input {margin:0; padding:0;}
    .font12 {font-size:12px;}
</style>


<section class="content">

    <?php if($error) : ?>
        <div class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <span><?php echo $error; ?></span>
        </div>
    <?php endif ?>
    <?php if($success) : ?>
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon fa fa-check"></i> 成功</h4>
            <?php echo $success; ?>
        </div>
    <?php endif ?>

    <div class="box box-primary">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-search"></i> 用户列表</h3>
        </div>

        <div class="box-body" id="vbody">

            <table id="logtable" class="table table-bordered table-striped dataTable table-hover " role="grid" aria-describedby="example1_info">
                <thead>
                <tr>
                    <th class="" rowspan="1" colspan="1" width="50" style="text-align:center">ID</th>
                    <th class="" rowspan="1" colspan="1" width="300" style="text-align:center;">LYFUID</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center;">鸭子ID</th>
                    <th class="" rowspan="1" colspan="1" width="60" style="text-align:center">头像</th>
                    <th class="" rowspan="1" colspan="1" width="150" style="text-align:center">昵称</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">剩余星星</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">累计星星</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">等级</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">经验</th>
                    <th class="" rowspan="1" colspan="1" width="80" style="text-align:center">饲料</th>
                    <th class="" rowspan="1" colspan="1" width="150" style="text-align:center">创建时间</th>
                    <th class="" rowspan="1" colspan="1" style="text-align:center">鸭子信息</th>
                </tr>
                </thead>
                <tbody>
                <?php if(!empty($all_user)) { foreach($all_user as $user) { ?>
                    <tr role="row" style="text-align:center;">
                        <td><?php echo $user['id']; ?></td>
                        <td class="font12" title="<?php echo $user['openid'];?>"><?php echo strlen($user['openid'])>32 ? substr($user['openid'],0,19).'...' : $user['openid']; ?></td>
                        <td><?php echo $user['duckId']; ?></td>
                        <td><?php echo $user['avatar'] ? '<img src="'.$user['avatar'].'" width="60" height="60" />' : '-'; ?></td>
                        <td><?php echo $user['nickName'] ? $user['nickName'] : '-'; ?></td>
                        <td><?php echo $user['star']; ?></td>
                        <td><?php echo $user['totalStar']; ?></td>
                        <td><?php echo $user['level']; ?></td>
                        <td><?php echo $user['exp']; ?></td>
                        <td><?php echo $user['fodder']; ?></td>
                        <td class="font12"><?php echo date('Y-m-d H:i:s',$user['createTime']); ?></td>
                        <td style="text-align:left;">
                            <?php $d = $ducks[$user['duckId']] ?? []; ?>
                            <table class="table table-bordered table-striped" style="width:100%;border-color:#aaa;">
                                <tr>
                                    <th>喂食</th>
                                    <th>星星</th>
                                    <th>套装</th>
                                    <th>状态</th>
                                    <th>出门时间</th>
                                    <th>回来时间</th>
                                    <th>最后检查偷</th>
                                    <th>剩余饲料</th>
                                    <th>开始喂食</th>
                                    <th>最后更新</th>
                                </tr>
                                <tr style="text-align:center;font-size:12px;border-color:#aaa;">
                                    <td><?php echo $d['feedCount']; ?></td>
                                    <td><?php echo $d['waitGainStar']; ?></td>
                                    <td><?php echo $d['dressupId']; ?></td>
                                    <td><?php switch($d['status']) { case 1: echo '家中'; break;case 2: echo '偷吃中'; break; case 4: echo '生气中'; break; } ?></td>
                                    <td><?php echo $d['startTime'] > 0 ? date('Y-m-d',intval($d['startTime']/1000)).'<br>'.date('H:i:s',intval($d['startTime']/1000)) : '-'; ?></td>
                                    <td><?php echo $d['backTime'] > 0 ? date('Y-m-d',intval($d['backTime']/1000)).'<br>'.date('H:i:s',intval($d['backTime']/1000)) : '-'; ?></td>
                                    <td><?php echo $d['lastCheckSteal'] > 0 ? date('Y-m-d',intval($d['lastCheckSteal']/1000)).'<br>'.date('H:i:s',intval($d['lastCheckSteal']/1000)) : '-'; ?></td>
                                    <td><?php echo $d['leftFodder']; ?></td>
                                    <td><?php echo $d['startFeedTime'] ? date('Y-m-d',$d['startFeedTime']).'<br>'.date('H:i:s',$d['startFeedTime']) : '-'; ?></td>
                                    <td><?php echo $d['updateFeedTime'] ? date('Y-m-d',$d['updateFeedTime']).'<br>'.date('H:i:s',$d['updateFeedTime']) : '-'; ?></td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                <?php } } ?>
                </tbody>
            </table>

            <?php pagination('game_user.php', $_GET, $page, $total, $pagesize); ?>

</section>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/vue.min.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>

<script type="text/javascript">
    var app = new Vue({
        el: '#vbody',
        data: {
            // 全局
            group_data: $.parseJSON('<?php echo $group_json; ?>'),
            all_func_ids: $.parseJSON('<?php echo json_encode($func_ids); ?>'),

            // 新增管理员
            new_groupid: '',
            new_user_name: '',
            new_password: '',
            new_current_group_funcs: [],

            action_aid: '',
            action_admin_name: '',

            change_password: '',

            // 修改分组
            change_group_id: '',
            change_funcs: [],
            change_extra: ''
        },
        methods: {
            setChangePassword: function(aid) {
                this.action_aid = aid;
            },
            new_change_group: function(e) {
                if(this.new_groupid) {
                    this.new_current_group_funcs = this.group_data[this.new_groupid]['funcs'].split(',');
                }
            },
            submitAddAdmin: function() {
                if(!this.new_groupid) { alert('必须选择分组'); return false; }
                if(!this.new_user_name) { alert('账号名不可为空'); return false; }
                if(!this.new_password) { alert('密码不可为空'); return false; }
                var group_funcs = this.new_current_group_funcs.join(',');
                var go = false;
                if(group_funcs.length < 1) {
                    if(confirm('确认创建这个无任何权限的账号吗?')) {
                        go = true;
                    }
                } else go = true;
                if(go === true) {
                    location.href = 'super_user.php?action=new_admin&groupid=' + this.new_groupid + '&username='
                        + this.new_user_name + '&password=' + this.new_password + '&funcs=' + group_funcs;
                }
            },
            freeze: function(aid) {
                if(confirm('确定要冻结该账号吗?')) {
                    location.href = 'super_user.php?action=freeze&aid='+aid;
                }
            },
            unFreeze: function(aid) {
                if(confirm('确定要解冻该账号吗?')) {
                    location.href = 'super_user.php?action=unfreeze&aid='+aid;
                }
            },
            delaccount: function(aid) {
                if(confirm('确定要删除该账号吗?')) {
                    location.href = 'super_user.php?action=delete&aid='+aid;
                }
            },
            submitChangePassword: function() {
                if(this.action_aid.length < 1) { alert('未指定操作用户'); return false; }
                if(this.change_password.length < 1) { alert('密码不可为空'); return false; }
                location.href = 'super_user.php?action=change_pass&aid='+this.action_aid+'&new_pass='+this.change_password;
            },
            openModal: function(aid, gid, username, extra) {
                this.action_aid         = aid;
                this.change_group_id    = gid;
                this.action_admin_name  = username;
                if(extra.length > 0) this.change_extra = '<span style="color:#f00;">是, 已配置额外的权限</span>'; else this.change_extra = '<span style="color:green">否</span>';
                var old_funcs_arr       = this.group_data[gid]['funcs'].split(',');
                var extra_funcs_arr     = extra.split(',');
                var merge_funcs_arr     = [];
                for(kk in old_funcs_arr) {
                    var need_del = false;
                    for(k in extra_funcs_arr) {
                        if(extra_funcs_arr[k] < 0 && Math.abs(extra_funcs_arr[k]) == old_funcs_arr[kk]) {
                            need_del = true;
                            break;
                        }
                    }
                    if(need_del === false) merge_funcs_arr.push(old_funcs_arr[kk]);
                }
                for(k in extra_funcs_arr) {
                    if(extra_funcs_arr[k] > 0) {
                        merge_funcs_arr.push(extra_funcs_arr[k]);
                    }
                }
                this.change_funcs = merge_funcs_arr;
            },
            change_funcs_group: function() {
                this.change_funcs = this.group_data[this.change_group_id]['funcs'].split(',');
            },
            submitChangeFuncs: function() {
                location.href = 'super_user.php?action=change_funcs&admin_id='+this.action_aid+'&new_group='+this.change_group_id+'&all_funcs='+this.change_funcs;
            }
        }
    });

    $('#modal-add-admin').on('hidden.bs.modal', function() {
        app.new_groupid = '';
        app.new_user_name = '';
        app.new_password = '';
        app.new_current_group_funcs = [];
    });
    $('#modal-change-password').on('hidden.bs.modal', function() {
        app.change_password = '';
        app.action_aid = '';
    });
    $('#modal-change-funcs').on('hidden.bs.modal', function() {
        app.action_aid = '';
        app.action_admin_name = '';
        app.change_group_id = '';
        app.change_extra = '';
        app.change_funcs = [];
    });

    $(function() {
        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);
    });
</script>

</body>
</html>
